package pw.hais.http.base;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;

import org.json.JSONObject;

import java.io.File;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import pw.hais.app.UtilConfig;
import pw.hais.utils.L;

/**
 * Created by Hais1992 on 2015/8/25.
 */
public class GetRequest {
    private static MediaType type = MediaType.parse("application/octet-stream;charset=" + UtilConfig.CHARSET);
    private static Object getRequest;

    /**
     * 添加一个网络请求
     *
     * @param method
     * @param url
     * @param header
     * @param params
     * @param body
     * @param <T>
     * @return
     */
    public static <T> Request requestBaseHttp(Method method, String url, Map<String, String> header, Map<String, String> params, T body) {
        //处理URL，各种初始化
        Request.Builder builder = new Request.Builder().url(url).tag(url);
        RequestBody requestBody = null;

        //处理Header
        if (header != null) {
            for (String key : header.keySet()) {
                String value = header.get(key);
                if (value == null) L.e(BaseHttp.TAG, "注意：参数" + key + "为 null。");
                builder.addHeader(key, value);
            }
        }

        //处理Body参数
        if (body != null) {
            Class<?> clazz = body.getClass();
            if (clazz == JSONObject.class) {
                //格式：  {"objectId": "123","username": "hais1992"}
                requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body.toString());
            } else if (clazz == HashMap.class) {
                //格式：a=123&b=123&b=123&b=123
                FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
                for (Map.Entry<String, String> entry : ((Map<String, String>) body).entrySet()) {
                    formEncodingBuilder.addEncoded(entry.getKey(), entry.getValue());
                }
                requestBody = formEncodingBuilder.build();
            } else if (body.getClass() == File.class) {
                requestBody = RequestBody.create(type, (File) body);
            } else if (body.getClass() == byte[].class) {
                requestBody = RequestBody.create(type, (byte[]) body);
            } else { //纯文本
                requestBody = RequestBody.create(type, body.toString());
            }
        }


        //根据类型不同，处理params
        switch (method) {
            case GET:
                if (params != null) builder = getGetRequest(url, builder, params);
                break;
            case POST:
                //if(params!=null)builder = getPostRequest(builder, params);
                if(requestBody!=null)builder.post(requestBody);
                break;
            case PUT:
                if(requestBody!=null)builder.put(requestBody);
                break;
            case DELETE:
                if(requestBody!=null)builder.delete(requestBody);
                break;
        }

        if (method != Method.GET || params == null) L.i(BaseHttp.TAG, method + "地址：" + url);
        if (header != null) L.i(BaseHttp.TAG, "Header：" + UtilConfig.GSON.toJson(header));
        if (body != null) L.i(BaseHttp.TAG, "Body：" + body);
        if (params != null) L.i(BaseHttp.TAG, "Params：" + UtilConfig.GSON.toJson(params));

        return builder.build();
    }

    /**
     * GET请求拼接参数到URL
     */
    public static Request.Builder getGetRequest(String url, Request.Builder builder, Map<String, String> params) {
        try {
            StringBuffer sb = new StringBuffer();
            for (String key : params.keySet()) {
                String value = params.get(key);
                if (value == null) {
                    L.e(BaseHttp.TAG, "注意：参数" + key + "为 null ,已自动更换为空字符串。");
                    value = "";
                }
                sb.append(key).append("=").append(URLEncoder.encode(value, UtilConfig.CHARSET)).append("&");
            }
            if (sb.length() != 0) url = url + "?" + sb;
        } catch (Exception e) {
            L.e(BaseHttp.TAG, "请求网络参数错误，不能为null。", e);
        }
        L.i("GET地址：" + url);
        return builder.url(url).tag(url);
    }

    /**
     * POST请求拼接表单
     */
    private static Request.Builder getPostRequest(Request.Builder builder, Map<String, String> params) {
        if (params == null) return builder;
        FormEncodingBuilder post_builder = new FormEncodingBuilder();
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) L.e(BaseHttp.TAG, "注意：参数" + key + "为 null。");
            post_builder.add(key, value);
        }
        return builder.post(post_builder.build());
    }

    /**
     * 上传文件
     *
     * @param url      请求地址
     * @param files    文件，可多文件
     * @param fileKeys
     * @param params   参数
     * @return
     */
    public static Request requestFile(String url, File[] files, String[] fileKeys, Map<String, String> header, Map<String, String> params) {
        MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
        for (String key : params.keySet()) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""), RequestBody.create(null, params.get(key)));
        }

        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String fileName = file.getName();

                String contentTypeFor = URLConnection.getFileNameMap().getContentTypeFor(fileName);
                if (contentTypeFor == null) contentTypeFor = "application/octet-stream";

                RequestBody fileBody = RequestBody.create(MediaType.parse(contentTypeFor), file);
                //TODO 根据文件名设置contentType
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody);
            }
        }

        Request.Builder builders = new Request.Builder().url(url).post(builder.build()).tag(url);
        if (header != null) {
            for (String key : header.keySet()) {
                String value = header.get(key);
                if (value == null) L.e(BaseHttp.TAG, "注意：参数" + key + "为 null。");
                builders.addHeader(key, value);
            }
            L.i(BaseHttp.TAG, "Header：" + UtilConfig.GSON.toJson(header));
        }
        Request request = builders.build();
        return request;
    }

    public static Request requestImage(String url) {
        Request request = new Request.Builder().url(url).tag(url).build();
        return request;
    }


    public static Request requestDownload(String url, String destFileDir) {
        Request request = new Request.Builder().url(url).tag(url).build();
        return request;
    }

}
